#### Figure 1: Norm Violations and Violence Support (Aggregate) ####

# Libraries
# library(here)
# library(rio)
# library(tidyverse)
# library(ggthemes)
# library(srvyr)

# data_pnas = import(here("Data","data_pnas.rds"))
# source(here("Code","Functions","funcs_theme.R"))

violence_ind = paste0("violence",1:6,"re")
norm_ind = paste0("norm_",c("judges","polling","censorship","loyalty"),"re")

cs_summary_agg = data_pnas |> 
  select(all_of(c(violence_ind, norm_ind)),
         uid, weight) |> 
  pivot_longer(-c("uid","weight"), names_to = "var", values_to = "val") |> 
  as_survey_design(ids = uid, weights = weight) |> 
  group_by(var) |> 
  summarise(val_sum = survey_mean(val, na.rm = T, vartype = "ci")) |> 
  ungroup() 

cs_summary_agg<- cs_summary_agg |> filter(var != "violence1re") |>
  filter(var != "violence2re") 

cs_summary_agg<- cs_summary_agg |>  mutate(var_typ = ifelse(str_detect(var,"norm"), "Democratic Norms", "Violence"),
                                           var = recode_factor(var,
                                                               norm_pollingre = "Reduce outparty polling stations",
                                                               norm_loyaltyre = "More loyal to party than Constitution\nin contested elections",
                                                               norm_judgesre = "Ignore outparty court decisions",
                                                               norm_executivere = "President should circumvent Congress",
                                                               norm_censorshipre = "Censor partisan media",
                                                               violence6re = "Murder",
                                                               violence5re = "Assault with deadly weapon",
                                                               violence4re = "Arson",
                                                               violence3re = "Assault",
                                                               violence2re = "Vandalism",
                                                               violence1re = "Protest without permit")
)

fig_1 = cs_summary_agg |> 
  ggplot(aes(x = val_sum, y = tidytext::reorder_within(var, val_sum,var_typ), 
             label = paste0(round(val_sum,3)*100,"%"))) +
  geom_pointrange(aes(xmin = val_sum_low,
                      xmax = val_sum_upp)) +
  geom_text(aes(x = val_sum + .13)) +
  facet_wrap(~ var_typ, scales = "free_y", ncol=1) +
  force_panelsizes(rows = c( 1,.85)) +
  scale_x_continuous(labels = scales::percent,
                     limits = c(0,1)) +
  tidytext::scale_y_reordered() +
  labs(x = "Percent Support",
       y = NULL) +
  theme_prl(base_family = "Helvetica")

print(fig_1)

ggsave(here("Plots","Main","figure_1.pdf"),
       fig_1,
       units = "in",
       width = 5, height = 3.5,
       dpi = 600)